#!/bin/sh
# This is a ShellScript For Auto Install LNMP and Moodle on CentOS
# Add executive privilege
# chmod 755 freebsd12.sh
# Powered by hongm
# Visted http://hongm.emoodle.org
# Modify 2016-05-10
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

##Download Server##
Download_Mirror="http://hongm.emoodle.org:8080/down"
##Moodle WebSite Home Directory##
Default_Moodle_Dir="/usr/local/www"

#ConfigFiles
NginxConfigFile="/usr/local/etc/nginx/nginx.conf"
MySQLConfigFile="/var/db/mysql/my.cnf"
PHPConfigFile="/usr/local/etc/php.ini"
FPMConfigFile="/usr/local/etc/php-fpm.d/www.conf"

# Check if user is root
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script"
    exit 1
fi

clear
echo ""
if uname -a | grep -Eqi "FreeBSD" ; then
    if uname -a | grep -Eqi "12."; then
        FreeBSD_Ver='12'
        FreeBSD_Version=$( uname -a | awk -F" " '{print $3}' | awk -F"-" '{print $1}' )
        #Check IP Configure File
        #Network_Config=$( ls /etc/sysconfig/network-scripts/ | grep ifcfg-eno )
        echo -e " \e[0;33mYour Current FreeBSD Version: \e[0;31m${FreeBSD_Version}\e[0m"
        IP=$( ifconfig  | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}' )
     else
        echo -e " \e[0;31mYour OS is not FreeBSD 12 !\e[0m"
        exit 1
    fi
 else
    echo -e " \e[0;31mYour OS is not FreeBSD!\e[0m"
    exit 1
fi

#set MySQL root password
echo "======================================================="
DB_Root_PWD="123456"
echo -e " \e[0;33mPlease setup root password of MySQL.(Default password: 123456)\e[0m"
read -p "Please enter: " DB_Root_PWD
if [ "${DB_Root_PWD}" = "" ]; then
     DB_Root_PWD="123456"
fi
echo -e " \e[0;32mMySQL root password: \e[0;31m${DB_Root_PWD}\e[0m"

#set Moodle admin email
echo "======================================================="
MoodleAdminEmail="admin@163.com"
echo -e " \e[0;33mPlease setup E-mail of Moodle Admin.(Default email: admin@163.com)\e[0m"
read -p "Please enter: " MoodleAdminEmail
if [ "${MoodleAdminEmail}" = "" ]; then
     MoodleAdminEmail="admin@163.com"
fi
echo -e " \e[0;32mMoodle admin E-mail: \e[0;31m${MoodleAdminEmail}\e[0m"

echo ""
echo "Press any key to install...or Press Ctrl+c to cancel"
OLDCONFIG=`stty -g`
stty -icanon -echo min 1 time 0
dd count=1 2>/dev/null
stty ${OLDCONFIG}

export ASSUME_ALWAYS_YES=YES
# Check Download Mirror
if [ "${Download_Mirror}" = "http://hongm.emoodle.org:8080/down" ]; then
    mirror_code=`curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://hongm.emoodle.org:8080/down/`
    if [ "${mirror_code}" != "200" ]; then
        mirror_code=`curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} https://study.wjszzx.com.cn/soft/`
        if [ "${mirror_code}" = "200" ]; then
            echo "Change to mirror https://study.wjszzx.com.cn/soft"
            Download_Mirror='https://study.wjszzx.com.cn/soft'
         else
            echo "Dwonload Server Error!"
            exit 1
        fi
    fi
fi

echo -e " \e[0;31m[+] Pkg installing Nginx+MySQL+PHP ...\e[0m"
pkg update --force
MoodlePHP_ver=` pkg search ^moodle | awk -F" " '{print$1}' | sed -n '$p' `
MySQL_ver=` pkg search ^mysql56-server | awk -F" " '{print$1}' `
Nginx_ver=` pkg search ^nginx-1 | awk -F" " '{print$1}' `
n=0
flag=1
while [ $n -le 8 -a $flag -gt 0 ]
do
    pkg -y install  ${MoodlePHP_ver} ${MySQL_ver} ${Nginx_ver}  wget sudo curl
    flag=$?
    n=$((n+1))
done
if [ $n -ge 8 ]; then
    echo -e "\e[0;31m[+] Pkg install Error!\e[0m"
    exit 1
fi
rm -fr php_info.txt

echo -e " \e[0;32m[+] Modify MySQL config ...\e[0m"
/usr/local/etc/rc.d/mysql-server onestart
/usr/local/bin/mysqladmin -u root password ${DB_Root_PWD}
cat > /tmp/mysql_sec_script<<EOF
update mysql.user set password=password('${DB_Root_PWD}') where user='root';
delete from mysql.user where not (user='root');
drop database test;
grant all on moodle.* to 'moodle'@'localhost' identified by '${DB_Root_PWD}';
grant all on moodle.* to 'moodle'@'127.0.0.1' identified by '${DB_Root_PWD}';
CREATE DATABASE moodle DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
flush privileges;
EOF
/usr/local/bin/mysql -u root -p${DB_Root_PWD} -h localhost < /tmp/mysql_sec_script
rm -f /tmp/mysql_sec_script
cat > ${MySQLConfigFile}<<EOF
[mysqld]
binlog_format=mixed
innodb_buffer_pool_size = 128M
innodb_file_per_table	= 1
innodb_file_format	= Barracuda
innodb_file_format_check= 1
innodb_file_format_max 	= Barracuda
innodb_strict_mode	= OFF
innodb_large_prefix	= 1
character-set-server 	= utf8mb4
collation-server 	= utf8mb4_unicode_ci
EOF
/usr/local/etc/rc.d/mysql-server onerestart

echo -e " \e[0;32m[+] Modify PHP config ...\e[0m"
cp /usr/local/etc/php.ini-production ${PHPConfigFile}
sed -i '' -e 's/post_max_size = 8M/post_max_size = 2048M/g' ${PHPConfigFile}
sed -i '' -e 's/upload_max_filesize = 2M/upload_max_filesize = 2048M/g' ${PHPConfigFile}
sed -i '' -e 's/max_execution_time = 30/max_execution_time = 300/g' ${PHPConfigFile}
sed -i '' -e 's/max_input_time = 60/max_input_time = 600/g' ${PHPConfigFile}
sed -i '' -e 's/default_socket_timeout = 60/default_socket_timeout = 600/g' ${PHPConfigFile}
sed -i '' -e 's/memory_limit = 128M/memory_limit = 512M/g' ${PHPConfigFile}
sed -i '' -e 's/;listen.owner = www/listen.owner = www/g' ${FPMConfigFile}
sed -i '' -e 's/;listen.group = www/listen.group = www/g' ${FPMConfigFile}
sed -i '' -e 's/pm.max_children = 5/pm.max_children = 50/g' ${FPMConfigFile}
sed -i '' -e 's/pm.start_servers = 2/pm.start_servers = 20/g' ${FPMConfigFile}
sed -i '' -e 's/pm.min_spare_servers = 1/pm.min_spare_servers = 5/g' ${FPMConfigFile}
sed -i '' -e 's/pm.max_spare_servers = 3/pm.max_spare_servers = 35/g' ${FPMConfigFile}
sed -i '' -e 's/;pm.max_requests = 500/pm.max_requests = 50000/g' ${FPMConfigFile}

echo -e " \e[0;32m[+] Modify Nginx config ...\e[0m"
mv ${NginxConfigFile} ${NginxConfigFile}.old
echo "worker_processes  auto;" > ${NginxConfigFile}
echo "events {" >> ${NginxConfigFile}
echo "    worker_connections  1024;" >> ${NginxConfigFile}
echo "    use kqueue;" >> ${NginxConfigFile}
echo "}" >> ${NginxConfigFile}
echo "http {" >> ${NginxConfigFile}
echo "    include       mime.types;" >> ${NginxConfigFile}
echo "    default_type  application/octet-stream;" >> ${NginxConfigFile}
echo "    sendfile        on;" >> ${NginxConfigFile}
echo "    tcp_nopush     on;" >> ${NginxConfigFile}
echo "    keepalive_timeout  65;" >> ${NginxConfigFile}
echo "    client_max_body_size 2048m;" >> ${NginxConfigFile}
echo "    fastcgi_connect_timeout 300;" >> ${NginxConfigFile}
echo "    fastcgi_send_timeout 300;" >> ${NginxConfigFile}
echo "    fastcgi_read_timeout 300;" >> ${NginxConfigFile}
echo "    server {" >> ${NginxConfigFile}
echo "        listen       80;" >> ${NginxConfigFile}
echo "        server_name  localhost;" >> ${NginxConfigFile}
echo "        root   ${Default_Moodle_Dir}/moodle;" >> ${NginxConfigFile}
echo "        index  index.php index.html index.htm;" >> ${NginxConfigFile}
echo "        error_page   500 502 503 504  /50x.html;" >> ${NginxConfigFile}
echo "        location = /50x.html {" >> ${NginxConfigFile}
echo "            root   /usr/local/www/nginx-dist;" >> ${NginxConfigFile}
echo "        }" >> ${NginxConfigFile}
echo "        location ~ \.php$ {" >> ${NginxConfigFile}
echo "            fastcgi_pass   127.0.0.1:9000;" >> ${NginxConfigFile}
echo "            fastcgi_index  index.php;" >> ${NginxConfigFile}
echo '            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;' >> ${NginxConfigFile}
echo "            include        fastcgi_params;" >> ${NginxConfigFile}
echo "        }" >> ${NginxConfigFile}
echo '        if (!-e $request_filename) {' >> ${NginxConfigFile}
echo '            rewrite "^(.*\.php)(/)(.*)$" $1?file=/$3 last;' >> ${NginxConfigFile}
echo "        }" >> ${NginxConfigFile}
echo "    }" >> ${NginxConfigFile}
echo "}" >> ${NginxConfigFile}

if cat /etc/rc.conf | grep nginx ; then
    echo "NMPM is enable"
 else
    echo mysql_enable="YES" >> /etc/rc.conf
    echo php_fpm_enable="YES" >> /etc/rc.conf
    echo nginx_enable="YES" >> /etc/rc.conf
fi
/usr/local/etc/rc.d/nginx restart
/usr/local/etc/rc.d/php-fpm restart

echo -e " \e[0;32m[+] Install Moodle ...\e[0m"
echo '<?PHP  // Moodle configuration file' > ${Default_Moodle_Dir}/moodle/config.php
echo 'unset($CFG);' >> ${Default_Moodle_Dir}/moodle/config.php
echo 'global $CFG;' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG = new stdClass();' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dbtype    = "mariadb";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dblibrary = "native";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dbhost    = "127.0.0.1";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dbname    = "moodle";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dbuser    = "moodle";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dbpass    = "'${DB_Root_PWD}'";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->prefix    = "mdl_";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dboptions = array(' >> ${Default_Moodle_Dir}/moodle/config.php
echo '  "dbpersist" => 0,' >> ${Default_Moodle_Dir}/moodle/config.php
echo '  "dbport" => "",' >> ${Default_Moodle_Dir}/moodle/config.php
echo '  "dbsocket" => "",' >> ${Default_Moodle_Dir}/moodle/config.php
echo '  "dbcollation" => "utf8mb4_unicode_ci",' >> ${Default_Moodle_Dir}/moodle/config.php
echo ');' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->wwwroot   = "http://'${IP}'";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->dataroot  = "'${Default_Moodle_Dir}'/moodledata";' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->directorypermissions = 0750;' >> ${Default_Moodle_Dir}/moodle/config.php
echo '$CFG->admin = "admin";' >> ${Default_Moodle_Dir}/moodle/config.php
echo 'require_once(dirname(__FILE__) . "/lib/setup.php"); // Do not edit' >> ${Default_Moodle_Dir}/moodle/config.php
mkdir -p ${Default_Moodle_Dir}/moodledata
chown -R www:www ${Default_Moodle_Dir}/moodle
chown -R www:www ${Default_Moodle_Dir}/moodledata
chmod -R 750 ${Default_Moodle_Dir}/moodle
chmod -R 750 ${Default_Moodle_Dir}/moodledata
find ${Default_Moodle_Dir}/moodle -type f -exec chmod 0640 {} \;

n=0
while [ $n -le 8 -a ! -f /var/db/mysql/moodle/mdl_user.frm ]
do
    sudo -u www /usr/local/bin/php ${Default_Moodle_Dir}/moodle/admin/cli/install_database.php --lang=zh_cn --adminpass=${DB_Root_PWD} --adminemail=${MoodleAdminEmail} --fullname=ITCenter --shortname=ITCenter --agree-license
    n=$((n+1))
done
if [ $n -ge 8 ]; then
    echo "Network error! Please continue to install http://${IP} in the browser!"
 else
    /usr/local/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='firstname,lastname' WHERE name='alternativefullnameformat';"
    /usr/local/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='0' WHERE name='defaulthomepage';"
    /usr/local/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='CN' WHERE name='country';"
    /usr/local/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='Asia/Shanghai' WHERE name='timezone';"
    /usr/local/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='' WHERE name='docroot';"
    sudo -u www /usr/local/bin/php ${Default_Moodle_Dir}/moodle/admin/cli/mysql_compressed_rows.php -f
    echo "* * * * * www /usr/local/bin/php ${Default_Moodle_Dir}/moodle/admin/cli/cron.php >/dev/null" >> /etc/crontab
fi


#Check_Files
isNginx=""
echo "============================== Check install =============================="
echo "Checking ..."
if test -f ${NginxConfigFile} && test -f /usr/local/sbin/nginx ; then
    echo -e " \e[0;32mNginx: OK\e[0m"
    isNginx="ok"
 else
    echo -e " \e[0;31mError: Nginx install failed.\e[0m"
fi
isDB=""
if test -f /usr/local/bin/mysql && test -s /usr/local/bin/mysqld_safe && test -s ${MariaDBConfigFile} ; then
    echo -e " \e[0;32mMariaDB: OK\e[0m"
    isDB="ok"
 else
    echo -e " \e[0;31mError: MariaDB install failed.\e[0m"
fi
isPHP=""
if test -s /usr/local/sbin/php-fpm && test -s ${PHPConfigFile} && test -s /usr/local/bin/php ; then
    echo -e " \e[0;32mPHP: OK\e[0m"
    isPHP="ok"
 else
    echo -e " \e[0;31mError: PHP install failed.\e[0m"
fi
if test "$isNginx" == "ok" && test "$isDB" == "ok" && test "$isPHP" == "ok" ; then
    echo "------------------------------------------------------------------------------"
    echo "      moodle ${Moodle_Version} for FreeBSD 12 Server, Written by Hongm"
    echo "                 http://hongm.emoodle.org                               "
    echo "------------------------------------------------------------------------------"
    echo "  Nginx:   /usr/local/etc/rc.d/nginx {start|stop|reload|restart|status}       "
    echo "  MySQL: /usr/local/etc/rc.d/mysql-server {start|stop|reload|restart|status}"
    echo "  PHP-FPM: /usr/local/etc/rc.d/php-fpm {start|stop|reload|restart|status}     "
    echo "------------------------------------------------------------------------------"
    echo "  Moodle Web Site: http://${IP}                                         "
    echo "  Moodle Soucre directory: ${Default_Moodle_Dir}/moodle                 "
    echo "  Moodle Data directory: ${Default_Moodle_Dir}/moodledata               "
    echo "------------------------------------------------------------------------------"
    echo "  Moodle admin password: ${DB_Root_PWD}                                 "
    echo "------------------------------------------------------------------------------"
    echo "  MySQL root password: ${DB_Root_PWD}                                 "
    echo "------------------------------------------------------------------------------"
 else
    echo -e " \e[0;31mSorry,Failed to install LNMP!\e[0m"
    echo -e " \e[0;31mYou can download moodle-install.log from your server,and mail install.log to hongm@sina.com.\e[0m"
fi
